import React, { useState, useEffect, useMemo } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Info, HelpCircle } from "lucide-react";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

/**
 * 信息提示工具组件
 * @param {React.ReactNode} children - 提示内容
 * @returns 带提示功能的帮助图标组件
 */
const InfoTooltip = ({ children }) => (
  <TooltipProvider>
    <Tooltip>
      <TooltipTrigger asChild>
        <HelpCircle className="w-4 h-4 text-gray-400 cursor-pointer ml-1" />
      </TooltipTrigger>
      <TooltipContent>
        <p>{children}</p>
      </TooltipContent>
    </Tooltip>
  </TooltipProvider>
);

/**
 * 绝缘绳网尺寸计算器组件
 * 基于DL/T 5301-2013附录C规范计算封网宽度和长度
 * @param {Object} crossingPoint - 跨越点信息（包含杆塔距离、导线类型等）
 * @param {Object} project - 项目信息（预留参数）
 * @returns 绝缘绳网计算表单及结果展示组件
 */
export default function InsulationNettingCalculator({
  crossingPoint,
  project,
}) {
  // 状态管理：存储所有计算参数（使用驼峰命名规范）
  const [params, setParams] = useState({
    // Zx（风偏距离）计算参数
    wireDiameter: 47.85, // 导线直径 (mm)
    horizontalTension: 59000, // 水平放线张力 (N)
    wireWeightPerMeter: 41.7, // 导线单位长度重量 (N/m)
    insulatorStringLength: 10.0, // 绝缘子串长度 (m)
    crossingToTowerDistance: 0, // 跨越物至邻近杆塔的水平距离 (m)
    spanLength: 484, // 跨越档距 (m)

    // B（封网宽度）计算参数
    sameSideProjectionWidth: 5.35, // 同侧导线地线投影宽度 (m)

    // Lwa（封网长度）计算参数
    crossedLineDistance: 10.0, // 被跨电力线两边线间水平距离 (m)
    crossingAngle: 85, // 交叉角度 (°)
    singleSideProtectionLength: 10.0, // 单侧保护长度 (m)
  });

  /**
   * 监听跨越点信息变化，自动填充参数
   * 当crossingPoint更新时，从该对象中提取相关参数更新到状态
   */
  useEffect(() => {
    if (crossingPoint) {
      // 计算跨越物到最近杆塔的距离
      const leftTowerDist = crossingPoint.towerLeft?.distanceToRoad;
      const rightTowerDist = crossingPoint.towerRight?.distanceToRoad;
      let crossToTowerDist = 0;

      if (
        typeof leftTowerDist === "number" &&
        typeof rightTowerDist === "number"
      ) {
        crossToTowerDist = Math.min(leftTowerDist, rightTowerDist);
      } else if (typeof leftTowerDist === "number") {
        crossToTowerDist = leftTowerDist;
      } else if (typeof rightTowerDist === "number") {
        crossToTowerDist = rightTowerDist;
      }

      // 更新参数状态（保留原参数，只更新有值的部分）
      setParams((prev) => ({
        ...prev,
        // 从导线类型中提取直径（格式如"XXX-直径"）
        wireDiameter: crossingPoint.conductorType
          ? parseFloat(crossingPoint.conductorType.split("-")[1]) ||
            prev.wireDiameter
          : prev.wireDiameter,
        spanLength: crossingPoint.spanLength || prev.spanLength,
        crossingAngle: crossingPoint.crossingAngle || prev.crossingAngle,
        crossingToTowerDistance:
          crossToTowerDist || prev.crossingToTowerDistance,
      }));
    }
  }, [crossingPoint]);

  /**
   * 更新参数值的处理函数
   * @param {string} key - 参数名称（对应state中的key）
   * @param {string} value - 输入框的原始值（字符串）
   */
  const handleParamChange = (key, value) => {
    const numValue = parseFloat(value);
    // 仅在有效数字或空值时更新状态（空值表示清空输入）
    if (!isNaN(numValue) || value === "") {
      setParams((prev) => ({ ...prev, [key]: value === "" ? "" : numValue }));
    }
  };

  /**
   * 计算结果（使用useMemo缓存，仅参数变化时重新计算）
   * 包含风载体型系数、单位风压、风偏距离、封网宽度和长度等
   */
  const results = useMemo(() => {
    const {
      wireDiameter,
      horizontalTension,
      wireWeightPerMeter,
      insulatorStringLength,
      crossingToTowerDistance,
      spanLength,
      sameSideProjectionWidth,
      crossedLineDistance,
      crossingAngle,
      singleSideProtectionLength,
    } = params;

    // 校验风偏距离(Zx)计算所需参数
    const requiredZxParams = [
      wireDiameter,
      horizontalTension,
      wireWeightPerMeter,
      insulatorStringLength,
      spanLength,
    ];
    if (
      requiredZxParams.some((p) => p === "" || p === null || p === undefined)
    ) {
      return { error: "计算风偏距离(Zx)所需参数不完整。" };
    }
    if (horizontalTension <= 0 || wireWeightPerMeter <= 0 || spanLength <= 0) {
      return { error: "张力(H), 导线单重(ω)和档距(l)必须为正数。" };
    }

    // 1. 计算风载体型系数(k)
    // 规范：导线直径≤17mm时k=1.2，否则k=1.1
    const windLoadFactor = wireDiameter <= 17 ? 1.2 : 1.1;

    // 2. 计算单位长度风压(W4(10))
    // 公式：W4(10) = 0.0613 × k × d（d为导线直径，单位mm）
    const windPressurePerMeter = 0.0613 * windLoadFactor * wireDiameter;

    // 3. 计算风偏距离(Zx)
    // 公式：Zx = W4(10) × [m×(l-m)/(2H) + λ/ω]
    // 其中：m为跨越物至近塔距离，l为档距，H为水平张力，λ为绝缘子串长度，ω为导线单位重量
    const windDeviationDistance =
      windPressurePerMeter *
      ((crossingToTowerDistance * (spanLength - crossingToTowerDistance)) /
        (2 * horizontalTension) +
        insulatorStringLength / wireWeightPerMeter);

    // 校验封网宽度(B)计算所需参数
    const requiredBParams = [sameSideProjectionWidth];
    if (
      requiredBParams.some((p) => p === "" || p === null || p === undefined)
    ) {
      return {
        windDeviationDistance: windDeviationDistance.toFixed(2),
        windLoadFactor: windLoadFactor.toFixed(2),
        windPressurePerMeter: windPressurePerMeter.toFixed(2),
        error: "计算封网宽度(B)所需参数不完整。",
      };
    }

    // 4. 计算封网宽度(B)
    // 公式：B = 2×Zx + b（b为同侧导地线投影宽度）
    const nettingWidth = 2 * windDeviationDistance + sameSideProjectionWidth;
    // 封网宽度实际选用值：向上取整到最近的偶数
    const practicalNettingWidth = Math.ceil(nettingWidth / 2) * 2;

    // 校验封网长度(Lwa)计算所需参数
    const requiredLwaParams = [
      crossedLineDistance,
      crossingAngle,
      singleSideProtectionLength,
    ];
    if (
      requiredLwaParams.some((p) => p === "" || p === null || p === undefined)
    ) {
      return {
        windDeviationDistance: windDeviationDistance.toFixed(2),
        windLoadFactor: windLoadFactor.toFixed(2),
        windPressurePerMeter: windPressurePerMeter.toFixed(2),
        nettingWidth: nettingWidth.toFixed(2),
        practicalNettingWidth,
        error: "计算封网长度(Lwa)所需参数不完整。",
      };
    }
    if (crossingAngle <= 0 || crossingAngle >= 180) {
      return {
        windDeviationDistance: windDeviationDistance.toFixed(2),
        windLoadFactor: windLoadFactor.toFixed(2),
        windPressurePerMeter: windPressurePerMeter.toFixed(2),
        nettingWidth: nettingWidth.toFixed(2),
        practicalNettingWidth,
        error: "交叉角必须在 (0, 180) 度之间。",
      };
    }

    // 5. 计算封网长度(Lwa)
    // 公式：Lwa = n + B/sinα + B/tanα + 2×Lwb
    // 其中：n为被跨线两边线距离，α为交叉角，Lwb为单侧保护长度
    const crossingAngleRad = crossingAngle * (Math.PI / 180); // 角度转弧度
    const nettingLength =
      crossedLineDistance +
      nettingWidth / Math.sin(crossingAngleRad) +
      nettingWidth / Math.tan(crossingAngleRad) +
      2 * singleSideProtectionLength;
    // 封网长度实际选用值：向上取整
    const practicalNettingLength = Math.ceil(nettingLength);

    return {
      windLoadFactor: windLoadFactor.toFixed(2), // 风载体型系数(k)
      windPressurePerMeter: windPressurePerMeter.toFixed(2), // 单位长度风压(W4)
      windDeviationDistance: windDeviationDistance.toFixed(2), // 风偏距离(Zx)
      nettingWidth: nettingWidth.toFixed(2), // 封网宽度(B)理论值
      practicalNettingWidth, // 封网宽度(B)实际选用值
      nettingLength: nettingLength.toFixed(2), // 封网长度(Lwa)理论值
      practicalNettingLength, // 封网长度(Lwa)实际选用值
      error: null,
    };
  }, [params]);

  /**
   * 参数输入框组件（复用组件）
   * @param {string} id - 输入框ID（对应参数key）
   * @param {string} label - 输入框标签
   * @param {number|string} value - 输入值
   * @param {string} unit - 单位文本
   * @param {string} tooltip - 提示信息（可选）
   * @param {boolean} wide - 是否跨列显示（可选）
   * @returns 带标签和单位的输入框组件
   */
  const InputField = ({ id, label, value, unit, tooltip, wide }) => (
    <div className={wide ? "sm:col-span-2" : ""}>
      <Label htmlFor={id} className="text-sm font-medium flex items-center">
        {label}
        {tooltip && <InfoTooltip>{tooltip}</InfoTooltip>}
      </Label>
      <div className="flex items-center mt-1">
        <Input
          id={id}
          type="number"
          value={value}
          onChange={(e) => handleParamChange(id, e.target.value)}
          className="flex-grow"
        />
        {unit && <span className="ml-2 text-sm text-gray-500">{unit}</span>}
      </div>
    </div>
  );

  return (
    <Card className="bg-white shadow-sm">
      <CardHeader>
        <CardTitle>绝缘绳网尺寸计算</CardTitle>
        <CardDescription>
          根据 DL/T 5301-2013 附录 C 计算封网宽度和长度。
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
          {/* 风偏距离计算参数区域 */}
          <div className="sm:col-span-2 pb-4 border-b">
            <h4 className="text-md font-semibold text-gray-800">
              1. 风偏距离 (Zx) 计算参数
            </h4>
          </div>
          <InputField
            id="wireDiameter"
            label="导线直径 (d)"
            value={params.wireDiameter}
            unit="mm"
          />
          <InputField
            id="horizontalTension"
            label="水平放线张力 (H)"
            value={params.horizontalTension}
            unit="N"
          />
          <InputField
            id="wireWeightPerMeter"
            label="导线单位长度重量 (ω)"
            value={params.wireWeightPerMeter}
            unit="N/m"
          />
          <InputField
            id="insulatorStringLength"
            label="绝缘子串长度 (λ)"
            value={params.insulatorStringLength}
            unit="m"
          />
          <InputField
            id="spanLength"
            label="跨越档距 (l)"
            value={params.spanLength}
            unit="m"
            tooltip="从跨越点信息自动获取"
          />
          <InputField
            id="crossingToTowerDistance"
            label="跨越物至近塔水平距离 (m)"
            value={params.crossingToTowerDistance}
            unit="m"
            tooltip="从跨越点信息自动获取"
          />

          {/* 封网宽度计算参数区域 */}
          <div className="sm:col-span-2 pt-4 pb-4 border-b border-t">
            <h4 className="text-md font-semibold text-gray-800">
              2. 封网宽度 (B) 计算参数
            </h4>
          </div>
          <InputField
            id="sameSideProjectionWidth"
            label="同侧导地线投影宽度 (b)"
            value={params.sameSideProjectionWidth}
            unit="m"
            wide
          />

          {/* 封网长度计算参数区域 */}
          <div className="sm:col-span-2 pt-4 pb-4 border-b border-t">
            <h4 className="text-md font-semibold text-gray-800">
              3. 封网长度 (Lwa) 计算参数
            </h4>
          </div>
          <InputField
            id="crossedLineDistance"
            label="被跨电力线两边线间水平距离 (n)"
            value={params.crossedLineDistance}
            unit="m"
          />
          <InputField
            id="singleSideProtectionLength"
            label="单侧保护长度 (Lwb)"
            value={params.singleSideProtectionLength}
            unit="m"
          />
          <InputField
            id="crossingAngle"
            label="交叉角度 (α)"
            value={params.crossingAngle}
            unit="°"
            tooltip="从跨越点信息自动获取"
          />
        </div>

        {/* 计算结果展示区域 */}
        <div className="mt-6 pt-6 border-t">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">计算结果</h3>
          {results.error ? (
            <Alert variant="destructive">
              <Info className="h-4 w-4" />
              <AlertDescription>{results.error}</AlertDescription>
            </Alert>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <div className="p-3 bg-gray-50 rounded-lg text-center">
                <p className="text-sm text-gray-600">风载体型系数 (k)</p>
                <p className="text-xl font-bold text-gray-800">
                  {results.windLoadFactor}
                </p>
              </div>
              <div className="p-3 bg-gray-50 rounded-lg text-center">
                <p className="text-sm text-gray-600">单位长度风压 (W4)</p>
                <p className="text-xl font-bold text-gray-800">
                  {results.windPressurePerMeter} N/m
                </p>
              </div>
              <div className="p-3 bg-blue-50 rounded-lg text-center">
                <p className="text-sm text-blue-700">风偏距离 (Zx)</p>
                <p className="text-xl font-bold text-blue-800">
                  {results.windDeviationDistance} m
                </p>
              </div>
              <div className="p-3 bg-green-50 rounded-lg text-center">
                <p className="text-sm text-green-700">封网宽度 (B) - 理论</p>
                <p className="text-xl font-bold text-green-800">
                  {results.nettingWidth} m
                </p>
              </div>
              <div className="p-3 bg-green-100 rounded-lg text-center border-2 border-green-200">
                <p className="text-sm text-green-800 font-semibold">
                  封网宽度 (B) - 选用
                </p>
                <p className="text-2xl font-bold text-green-900">
                  {results.practicalNettingWidth} m
                </p>
              </div>
              <div className="p-3 bg-gray-50 rounded-lg text-center md:col-span-1"></div>
              <div className="p-3 bg-purple-50 rounded-lg text-center">
                <p className="text-sm text-purple-700">封网长度 (Lwa) - 理论</p>
                <p className="text-xl font-bold text-purple-800">
                  {results.nettingLength} m
                </p>
              </div>
              <div className="p-3 bg-purple-100 rounded-lg text-center border-2 border-purple-200">
                <p className="text-sm text-purple-800 font-semibold">
                  封网长度 (Lwa) - 选用
                </p>
                <p className="text-2xl font-bold text-purple-900">
                  {results.practicalNettingLength} m
                </p>
              </div>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}
